package create.rpc.registry;

import create.rpc.enumeration.RpcError;
import create.rpc.exception.RpcException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class DefaultServiceRegistry {

    private static final Logger logger = LoggerFactory.getLogger(DefaultServiceRegistry.class);

    //ConcurrentHashMap 是线程安全的
    private static final Map<String,Object> serviceMap = new ConcurrentHashMap<>();
    private static final Set<String> registeredService = ConcurrentHashMap.newKeySet();


    public synchronized  <T> void register(T service) {

        //getCanonicalName,得到class的name
        String serviceName = service.getClass().getCanonicalName();

        if (registeredService.contains(serviceName))
            return;

        registeredService.add(serviceName);
        Class<?>[] interfaces = service.getClass().getInterfaces();

        if (interfaces.length==0)
        {
            throw new RpcException(RpcError.SERVICE_NOT_IMPLEMENT_ANY_INTERFACE);
        }

        for (Class<?> clazz:interfaces)
        {
            serviceMap.put(clazz.getCanonicalName(),service);
        }

        logger.info("向接口: {} 注册服务: {}", interfaces, serviceName);
    }


    public synchronized Object getService(String serviceName) {

        Object service = serviceMap.get(serviceName);

        if (service==null)
        {
            throw new RpcException(RpcError.SERVICE_NOT_FOUND);
        }
        return service;
    }
}
